
import Vue from 'vue'
import axios from 'axios'
import { getWxAuthorize } from '@/libs/service'

axios.defaults.baseURL = process.env.VUE_APP_BASEURL
// 高德地图 允许 cross
axios.defaults.crossDomain = true

axios.interceptors.request.use(config => {
    config.data = config.data || {}
    // 高德地图 cross 不允许设置请求头
    if (!config.noheaders) {
        config.headers = {
            'token': Vue.prototype.$ls.getItem('token') || ''
        }
    }
    return config
})

// 添加响应拦截器
axios.interceptors.response.use(response => {
    if (response.data.code && response.data.code != '0000') {
        if (response.data.code == '9900') {
            // 超时微信重新授权
            Vue.prototype.$ls.removeItem('token')
            sessionStorage.removeItem('wxCode')
            getWxAuthorize()
            return Promise.reject(new Error('9900'))
        }
        return Promise.reject(new Error(response.data.message))
    }
    return response.data
}, error => {
    if (error.response) {
        return Promise.reject(new Error(error.data.message))
    }
    return Promise.reject(new Error('服务器繁忙'))
})

// 分页
axios.page = function (url, params) {
    return new Promise(function (resolve, reject) {
        axios({
            method: 'post',
            url: url,
            params: params
        }).then(res => {
            let result = res.data
            let data = result.records || {}
            let page = {
                current: result.current, // 当前页数/下一页页数
                size: result.size, // 每页显示页数
                hasNext: false,
                finishedText: ''
            }
            // 是否有下一页
            if (result.pages > result.current) {
                page.current = result.current + 1
                page.hasNext = true
            } else {
                page.hasNext = false
                page.finishedText = '没有更多了'
            }
            let response = {
                code: res.code,
                message: res.message,
                data: data,
                page: page
            }
            resolve(response)
        }).catch(err => {
            reject(err)
        })
    })
}

export default axios
